package com.lzy.service.impl;

import com.lzy.constant.CacheConstants;
import com.lzy.constant.Constants;
import com.lzy.context.LocalUser;
import com.lzy.enums.ExceptionEnums;
import com.lzy.exception.ServiceException;
import com.lzy.exception.user.CaptchaNoIncorrectException;
import com.lzy.exception.user.UserPasswordNotMatchException;
import com.lzy.manager.AsyncManager;
import com.lzy.manager.factory.AsyncFactory;
import com.lzy.security.LoginUser;
import com.lzy.service.ISysLoginService;
import com.lzy.utils.RedisCache;
import com.lzy.utils.StringUtil;
import com.lzy.utils.TokenUtil;
import com.lzy.vo.UserLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author lyw
 * @Date 2023/2/21-下午10:41
 */
@Service
public class SysLoginService implements ISysLoginService {

  @Value("${user.forced-offline.enabled}")
  private boolean enabled;

  @Autowired
  private TokenUtil tokenUtil;

  @Autowired
  private RedisCache redisCache;

  @Resource
  private AuthenticationManager authenticationManager;

  @Override
  public String login(UserLoginVo userLoginVo) throws IOException {
    // 验证用户验证吗
    String captchaKey = CacheConstants.CAPTCHA_CODE_KEY + userLoginVo.getUuid();
    String captcha = redisCache.getCacheObject(captchaKey);
    if (StringUtil.isEmpty(captcha) || !userLoginVo.getCode().equals(captcha)) {
      throw new CaptchaNoIncorrectException(ExceptionEnums.VERIFICATION_CODE_EXCEPTION.getCode(), ExceptionEnums.VERIFICATION_CODE_EXCEPTION.getMessage());
    }
    // 用户验证
    Authentication authentication = null;
    try
    {
      // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername方法 验证用户信息
      authentication = authenticationManager
              .authenticate(new UsernamePasswordAuthenticationToken(userLoginVo.getUsername(), userLoginVo.getPassword()));
    }
    catch (Exception e)
    {
      if (e instanceof BadCredentialsException)
      {
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(userLoginVo.getUsername(), Constants.LOGIN_FAIL, "user.password.not.match"));
        throw new UserPasswordNotMatchException();
      }
      else
      {
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(userLoginVo.getUsername(), Constants.LOGIN_FAIL, e.getMessage()));
        throw new ServiceException(ExceptionEnums.LOGIN_EXCEPTION.getCode(), ExceptionEnums.LOGIN_EXCEPTION.getMessage());
      }
    }
    // 记录用户信息
    LoginUser loginUser = (LoginUser) authentication.getPrincipal();
    SecurityContextHolder.getContext().setAuthentication(authentication);

    // 强制下限
    if (enabled) {
      String preUserToken = redisCache.getCacheObject(tokenUtil.getTokenKey(loginUser.getId()));
      if (StringUtil.isNotEmpty(preUserToken)) {
        redisCache.deleteObject(preUserToken);
        String preUserKey = tokenUtil.getUserKey(loginUser.getId(), preUserToken);
        if (StringUtil.isNotEmpty(preUserKey)) {
          redisCache.deleteObject(preUserKey);
        }
      }
    }

    // 返回 token 并缓存
    String token = tokenUtil.createToken(loginUser);
    AsyncManager.me().execute(AsyncFactory.recordLogininfor(userLoginVo.getUsername(), Constants.LOGIN_SUCCESS, "用户登陆成功"));
    return token;
  }

  @Override
  public String refreshToken() throws IOException {
    String token = tokenUtil.createToken(LocalUser.getLoginUser());
    return token;
  }
}
